<template>
  <Modal v-model="visible" width="800" title="修改渠道" @on-visible-change="closeAudio">
    <Form ref="form" :model="form" :rules="rules" :label-width="170">
      <FormItem label="当前客户来源渠道:">
        {{ data.channelName }}
      </FormItem>
      <FormItem label="当前渠道合作类型:">
        {{ data.cooperationTypeName || '无' }}
      </FormItem>
      <FormItem label="当前渠道费用:">
        <template v-if="data.channelCostValue">{{ data.channelCostValue }}元</template>
        <template v-else>无</template>
      </FormItem>
      <FormItem label="修改后客户来源渠道:" prop="channelSourceId">
        <!-- <Cascader v-model="form.channelSourceId" :data="channelOptions" @on-change="onChange">
        </Cascader> -->
        <div class="radioNine" v-if="visible">
          <RadioGroup :v-model="form.channelSourceId" @on-change="onChange" type="button">
            <Radio v-for="item in channelOptions" :key="item.channelId"
              :label="item.channelId">
              <!-- {{ item.channelName }} -->
              <span :title="item.channelName "
                style="display:inline-block;width:100%; overflow: hidden;white-space: nowrap; text-overflow: ellipsis;">
                {{ item.channelName  }}</span>
              <span v-if="item.isTakeLook=='1'" class="qu">渠</span>
              <span v-if="item.isNetAcquire=='1'" class="wang">网</span>
            </Radio>
          </RadioGroup>
        </div>
      </FormItem>
      <FormItem label="修改后渠道合作类型：" prop="cooperationType" v-if="cooperationFlag">
        <Select v-model="form.cooperationType" placeholder='请输入合作类型' clearable>
          <Option v-for="option in cooperationTypeFinal" :value="option.key" :key="option.key"
            :label="option.value">
          </Option>
        </Select>
      </FormItem>
      <FormItem label="修改后渠道合作类型:" v-else-if="form.channelSourceId">
        {{ form.cooperationTypeName || '无' }}
      </FormItem>
      <FormItem label="修改后渠道费用:"
        v-if="form.channelSourceId && form.cooperationType != '1' && form.cooperationType != '3'">
        无
      </FormItem>
      <FormItem
        v-if="form.channelSourceId && (form.cooperationType == '1' || form.cooperationType == '3')">
        <p slot="label" style="display: flex; justify-content: flex-end;">
          <span style="color: #ed4014; font-size: 20px; margin-right: 4px;">*</span>
          <label>修改后渠道费用:</label>
        </p>
        <Input v-model="form.channelCostValue" type="number" number placeholder="请输入">
        <span slot="append">
          <template
            v-if="form.channelCostType == '1'||form.channelCostType == '3'">元</template>
          <template v-if="form.channelCostType == '2'">%</template>
        </span>
        </Input>
      </FormItem>
      <FormItem label="渠道附件:" v-if="showFiles">
        <div style="display: flex; flex-wrap: wrap;">
          <template v-if="form.fileAddress.length">
            <div v-for="(file, index) in form.fileAddress" :key="index">
              <file-item :data="file" @remove="onRemove(index)" @preview="onPreview(index)" />
            </div>
          </template>
          <Upload ref="upload" name="multipartFile" multiple :action="upload.reqUrl"
            :headers="upload.headers" :data="upload.data" :show-upload-list="false"
            accept="image/png, image/jpg, image/jpeg" :before-upload="beforeUpload"
            :on-success="onSuccess" style="margin: 0 10px 10px 0;">
            <div
              style="width: 100px; height: 100px; line-height: 100px; text-align: center; border: 1px dashed #dadada; cursor: pointer;">
              <Icon type="ios-add" :size="30" />
            </div>
          </Upload>
        </div>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="onClose">取消</Button>
      <Button type="primary" @click="onConfirm">确定</Button>
    </div>

    <preview-image :images="preview.images" :showDownLoad="true" :showIndex="preview.showIndex"
      ref="preViewImage"></preview-image>
  </Modal>
</template>

<script>
  import fileItem from './file-item.vue'
  import toolMgr from '@/biz/base/tool.js'
  import channelMgr from '@/biz/channel/channel.js'
  import auditMgr from '@/biz/flowApproval/riskAudit.js'

  export default {
    props: {
      data: {
        type: Object,
        default: () => {}
      }
    },
    components: {
      fileItem
    },
    data() {
      return {
        cooperationTypeFinal: this.$dt.dictInfo().cooperationTypeFinal.filter(item => item
          .key != 6),
        cooperationFlag: false,
        visible: false,
        form: {
          cooperationType: '',
          cooperationTypeName: '',
          fileAddress: [],
          channelSourceId: null
        },
        rules: {
          channelSourceId: [
            { required: true, type: 'number', message: '请选择修改后客户来源渠道', trigger: 'change' },
          ],
          cooperationType: [
            { required: true, message: '请选择修改后渠道合作类型', trigger: 'change' },
          ]
        },
        channelOptions: [],
        showFiles: false,
        images: {},
        upload: toolMgr.unloadImage(),
        uploadList: [],
        preview: {
          images: [],
          showIndex: 0
        },
        businessId: null,
        annexLogList: [],
        channelIdOld: null
      }
    },
    methods: {
      onConfirm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if ((this.form.cooperationType == '1' || this.form.cooperationType == '3') && !
              this.form.channelCostValue) {
              this.$Message.error('修改后渠道费用不可为空')
              return
            }
            auditMgr.updateChannel({
              orderId: this.data.sId,
              channelSourceId: this.form.channelSourceId,
              channelCostValue: this.form.channelCostValue,
              fileAddress: this.form.fileAddress.length ? JSON.stringify(this.form
                .fileAddress) : '',
              cooperationType: this.form.cooperationType
            }).then(() => {
              this.$Message.success('修改成功')
              this.onClose()
              this.$emit('success')
            })
          }
        })
      },
      showChannelImgFun() {
        console.log(this.form.channelSourceId, this.channelIdOld, this.channelOptions,
          '55555555');
        let changeChannelId = this.form.channelSourceId ? this.form.channelSourceId :
          this.channelIdOld

        this.channleAnnexLogList().then(res => {
          let annexFiles = []
          let currentChannel = this.channelOptions.find(item => {
            return item.channelId == changeChannelId
          })
          console.log(currentChannel, 'currentChannelcurrentChannel');
          if (currentChannel && (currentChannel.isNetAcquire == '1' || currentChannel
              .isTakeLook ==
              '1')) {
            if (currentChannel.cooperationType != '7') {
              this.showFiles = true
              if (res && res.length) {
                let currentAnnex = res.find(annexItem => {
                  return annexItem.channelId == currentChannel.channelId
                })
                if (currentAnnex && currentAnnex.url) {
                  let annexUrl = JSON.parse(currentAnnex.url)
                  if (annexUrl && annexUrl
                    .length > 0) {
                    annexUrl.forEach(itemUrl => {
                      if (itemUrl) {
                        annexFiles.push({
                          name: itemUrl.date,
                          url: itemUrl.url
                        })
                      }
                    })
                    this.$set(this.form, 'fileAddress', annexFiles)
                  }
                } else {
                  this.$set(this.form, 'fileAddress', [])
                }
              }
            } else {
              this.showFiles = false
            }
          } else {
            this.showFiles = false
          }
          // if (this.showKey == 'channelName' && flag1) {
          //   this.filesFlag = true
          // } else {
          //   this.filesFlag = false
          // }
        })
      },
      onChange(val) {
        console.log(val, '选中ddddddd');
        this.form.channelSourceId = val

        this.showChannelImgFun()

        // let cooperationTypetype = null
        // let cooperationTypeName = null

        // this.channelOptions.forEach(item => {
        //   if (item.channelId == this.form.channelSourceId) {
        //     console.log(item, 'aaaaavvvvv');
        //     cooperationTypeName = item.cooperationTypeName
        //     cooperationTypetype = item.cooperationType

        //     if (item.isNetAcquire == '1' || item.isTakeLook == '1') {
        //       if (item.isNetAcquire == '1') {
        //         if (item.cooperationType == '7') {
        //           this.showFiles = false
        //         } else {
        //           this.showFiles = true
        //         }

        //         this.form.fileAddress = this.images.networkCertificateImage ? [...this
        //           .images.networkCertificateImage
        //         ] : []
        //       } else if (item.isTakeLook == '1') {
        //         if (item.cooperationType == '7') {
        //           this.showFiles = false
        //         } else {
        //           this.showFiles = true
        //         }
        //         this.form.fileAddress = this.images.channelTakeLook ? [...this.images
        //           .channelTakeLook
        //         ] : []
        //       } else {
        //         this.showFiles = false
        //       }
        //     } else {
        //       this.showFiles = false
        //     }
        //   }
        // })

        let cooperationTypetype = null
        let cooperationTypeName = null
        let currentChannel = this.channelOptions.find(item => {
          return item.channelId == this.form.channelSourceId
        })
        if (currentChannel) {
          cooperationTypeName = currentChannel.cooperationTypeName
          cooperationTypetype = currentChannel.cooperationType
        }

        this.form.cooperationType = cooperationTypetype
        this.form.cooperationTypeName = cooperationTypeName ?
          cooperationTypeName :
          '无'
        if (cooperationTypetype == '6') {
          this.cooperationFlag = true
          this.form.cooperationType = ''
        } else {
          this.cooperationFlag = false
        }


        // if (!value || !value.length) return
        // this.form = {
        //   ...this.form,
        //   ...selectedData[selectedData.length - 1]
        // }
        // // 渠道分类为网络媒体、渠道带看，显示渠道附件上传器及该渠道下已上传的附件图片缩略图
        // if (value[0] == '2') {
        //   this.showFiles = true
        //   this.form.fileAddress = [...this.images.networkCertificateImage]
        // } else if (value[0] == '3') {
        //   this.showFiles = true
        //   this.form.fileAddress = [...this.images.channelTakeLook]
        // } else {
        //   this.showFiles = false
        // }

        // if (selectedData[1].cooperationType == '6') {
        //   this.cooperationFlag = true
        //   this.form.cooperationType = ''
        // } else {
        //   this.cooperationFlag = false
        // }


      },
      beforeUpload(file) {
        this.uploadList.push(file)
        if (this.uploadList.length + this.form.fileAddress.length > 10) {
          this.$Message.warning('渠道附件最多可上传10张图片')
          return false
        } else {
          return true
        }
      },
      // 上传成功
      onSuccess(res, file, fileList) {
        if (res.code == '200') {
          this.form.fileAddress.push({
            url: res.data.imageURL,
            date: this.$tool.formatDate(new Date()),
          })
        } else {
          this.$Message.error(res.msg)
        }
      },
      // 删除
      onRemove(index) {
        this.form.fileAddress.splice(index, 1)
      },
      onPreview(index) {
        this.preview.images = this.form.fileAddress.map(i => (i.url))
        this.preview.showIndex = index
        this.$refs.preViewImage.show()
      },

      //获取渠道附件
      channleAnnexLogList() {
        let params = {
          businessId: this.businessId,
          housesId: this.data.buildingId,
          type: 'subscription',
        }
        return channelMgr.channleAnnexLogList(params)
          .then((res) => {
            this.annexLogList = res
            return res
          })
      },
      // 渠道列表
      getChannelList() {
        let params = {
          buildingId: this.data.buildingId,
          validate: 1,
          type: 1
        }
        return channelMgr.caseChannelListOrder(params)
          .then((res) => {
            console.log(333);
            console.log(res, 'dddddddddddddddd');
            this.channelOptions = res

            let cur = this.channelOptions.find(item => {
              return item.channelName == this.data.channelName
            })
            if (cur) {
              this.channelIdOld = cur.channelId
            }
            console.log(cur, this.channelIdOld, this.data.channelName, 'cccccccccc');

          })
          .catch((res) => {
            this.channelOptions = []
          })
      },
      // // 获取渠道
      // getChannles() {
      //   channelMgr.caseChannelTreeList(this.data.buildingId).then(res => {
      //     this.channelOptions = res
      //   })
      // },
      // 查看订单渠道附件
      // getChannelImages() {
      //   auditMgr.channelImages(this.data.orderReviewId).then(res => {
      //     console.log(res, '查订单渠道附件');
      //     this.images = { ...res }
      //   })
      // },
      onClose() {
        this.visible = false
        this.cooperationFlag = false
        this.form = {
          cooperationType: '',
          cooperationTypeName: '',
          fileAddress: [],
          channelSourceId: null
        }
        // this.$set(this.form, 'cooperationType', '')
        // this.$set(this.form, 'cooperationTypeName', '')
        // this.$set(this.form, 'channelSourceId', null)
        // this.$set(this.form, 'fileAddress', [])
        this.channelOptions = []
        this.showFiles = false
        this.images = {}
        this.$refs.form.resetFields()
      },
      closeAudio(res) {

        console.log(res, this.data, this.form, '33333333333');
        this.businessId = this.data.sId ? this.data.sId : null


        if (res && this.data.buildingId) {
          this.getChannelList().then(res => {
            this.showChannelImgFun()

          })

        } else {
          this.onClose()
          console.log(this.form)
          // this.$refs.form.resetFields()
        }
      },

    },
  }
</script>

<style lang='scss' scoped>
</style>